/**   
* @Title: AbstractSpiderSeedInitialization.java
* @Package org.xaoyaoyao.spider.init
* @Description: TODO
* @author xaoyaoyao
* @date Jan 25, 2019 2:23:26 PM
* @version V1.0   
*/
package org.xaoyaoyao.spider.init;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;
import org.xaoyaoyao.spider.entity.SpiderSeed;
import org.xaoyaoyao.spider.properties.SpiderConfiguration;
import org.xaoyaoyao.spider.redis.RedisService;
import org.xaoyaoyao.spider.util.Constants;
import org.xaoyaoyao.spider.util.ContextLoader;

/**
 * @ClassName: AbstractSpiderSeedInitialization
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 25, 2019 2:23:26 PM
 * 
 */
public abstract class AbstractSpiderSeedInitialization {

	private final static int FIFTEEN_MINUTES = 30 * 60;

	private RedisService redisService;

	private SpiderConfiguration spiderConfiguration;

	public void initRedisService() {
		this.redisService = null == redisService ? ContextLoader.getBean(RedisService.class) : redisService;
		this.spiderConfiguration = null == spiderConfiguration ? ContextLoader.getBean(SpiderConfiguration.class) : spiderConfiguration;
	}

	/**
	 * @Title: initializationData
	 * @Description: 初始化种子
	 * @return void
	 */
	public abstract List<SpiderSeed> initializationData();

	private void initSpiderSeeds() throws Exception {
		List<SpiderSeed> seeds = this.initializationData();
		if (CollectionUtils.isNotEmpty(seeds)) {
			Map<String, String> hash = new ConcurrentHashMap<String, String>();
			seeds.stream().forEach(seed -> {
				hash.put(seed.getId() + "", seed.toString());
			});
			long time = spiderConfiguration.getSeedCacheTime() <= 120 ? FIFTEEN_MINUTES : spiderConfiguration.getSeedCacheTime();
			redisService.hmset(Constants.SPIDER_SEED_KEYS, hash, time);
		} else {
			throw new Exception("List<SpiderSeed>为空，请初始化种子数据，即继承AbstractSeedInitialization类实现initializationData方法！！！");
		}
	}

	public void execute() throws Exception {
		initSpiderSeeds();
	}
}
